//
//  AddGuideViewController.m
//  ShoppingExperience
//
//  Created by LiYinDi on 15/11/13.
//  Copyright © 2015年 RuiBen. All rights reserved.
//

#import "AddGuideViewController.h"
#import "HZAreaPickerView.h"
#import "ZJSwitch.h"
@interface AddGuideViewController ()<HZAreaPickerDelegate>
{
    NSMutableArray *featureCodeArray;
    NSMutableArray *featureNameArray;
    NSMutableArray *selectFeatureCodeArray;
    NSMutableArray *selectFeatureNameArray;
    NSString *provinceStr;
    NSString *cityStr;
    NSString *regionStr;
    NSString *addressStr;
    NSString *sexStr;
   

}
@property (strong, nonatomic) NSString *areaValue, *cityValue;
@property (strong, nonatomic) HZAreaPickerView *locatePicker;
@end

@implementation AddGuideViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    featureCodeArray=[NSMutableArray array];
    featureNameArray=[NSMutableArray array];
    selectFeatureCodeArray=[NSMutableArray array];
    selectFeatureNameArray=[NSMutableArray array];
    provinceStr=@"";
    cityStr=@"";
    regionStr=@"";
    addressStr=@"";
    [_addShopGuideAlphaView setBackgroundColor:[Global parseColor:WESTORE_TRANSCLUCENT]];
    [_addShopGuideAlphaView addTarget:self action:@selector(addShopGuideAlphaViewClick) forControlEvents:UIControlEventTouchUpInside];
    
    _remarkTextView.layer.borderColor=[[UIColor colorWithRed:239.0f/255.0f green:239.0f/255.0f blue:239.0f/255.0f alpha:1] CGColor];
    _remarkTextView.layer.borderWidth= 1.0f;
    _remarkTextView.layer.cornerRadius=3;
    
    _remarkTextView.text=@"";
    _remarkTextViewImage.hidden=NO;
    _remarkTextViewLabel.hidden=NO;

    _addGuideSwitch1.backgroundColor = [UIColor clearColor];
    // _switch1.tintColor = [UIColor colorWithRed:45.0f/255.0f green:158.0f/255.0f blue:237.0f/255.0f alpha:1.0f];
    _addGuideSwitch1.onText = @"男";
    _addGuideSwitch1.onTintColor = [UIColor colorWithRed:45.0f/255.0f green:158.0f/255.0f blue:237.0f/255.0f alpha:1.0f];
    _addGuideSwitch1.tintColor = [UIColor colorWithRed:253.0f/255.0f green:129.0f/255.0f blue:182.0f/255.0f alpha:1.0f];
    
    _addGuideSwitch1.on=YES;

    sexStr=@"男";
    _addGuideSwitch1.offText = @"女";
    [_addGuideSwitch1 addTarget:self action:@selector(handleSwitchEvent:) forControlEvents:UIControlEventValueChanged];
    
    [self requestGuideTags];
    // Do any additional setup after loading the view from its nib.
}

- (void)handleSwitchEvent:(ZJSwitch *)sender
{
    if (sender.on==1) {
        sexStr=@"男";
    }
    else
    {
        sexStr=@"女";
    }
    //  NSLog(@"%d",sender.on);
}

-(void)addShopGuideAlphaViewClick
{
    if (self.view!=nil) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
        
    }
    
}

-(void)requestGuideTags
{
    // NSLog(@"##");
    if ([Global getLoginToken].length>0) {
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
        [params setObject:[Global getLoginToken] forKey:@"Token"];
        [HttpRequest requestData:@"ShopManager/GuideFeature" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                    [featureCodeArray removeAllObjects];
                    [featureNameArray removeAllObjects];
                    NSMutableArray *mFeaturesArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                    for (int i=0; i<mFeaturesArray.count; i++) {
                        [featureCodeArray addObject:[[mFeaturesArray objectAtIndex:i] objectForKey:@"FeatureCode"]];
                        [featureNameArray addObject:[[mFeaturesArray objectAtIndex:i] objectForKey:@"FeatureName"]];
                    }
                    //   NSLog(@"featureNameArray=%@",featureNameArray);
                    [self setTagView];
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    //  [Global showTextHud:requestResultStr view:self.view];
                    [Global showTextHudSub:requestResultStr view:self.view];
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    [Global loginViewController:self noteStr:requestResultStr];
                        // [Global loginViewController:self];
                    }
                    
                }
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
        }];
        
    }
}
-(void)setTagView
{
     CGRect frame=_tagView.frame;
    for (int i=0; i<featureNameArray.count; i++) {
        
        UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
        CGRect rect=button.frame;
        rect.size.height=32;
        rect.size.width=130;
        rect.origin.x=17+140*(i%6);
        rect.origin.y=22+46*(i/6);
        button.frame=rect;
        frame.size.height=22+32+46*(i/6);
        button.tag=i;
        [button setBackgroundColor:[UIColor clearColor]];
        button.layer.borderWidth=1;
        button.layer.borderColor=[[UIColor colorWithRed:239.0f/255.0f green:239.0f/255.0f blue:239.0f/255.0f alpha:1.0f] CGColor];
        button.layer.cornerRadius=16;
        button.titleLabel.font = [UIFont systemFontOfSize: 15.0];
        [button setTitleColor:[UIColor colorWithRed:100.0f/255.0f green:100.0f/255.0f blue:100.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];
        
        //  [button setBackgroundColor:[UIColor colorWithRed:245.0f/255.0f green:245.0f/255.0f blue:245.0f/255.0f alpha:1.0f]];
        [button setTitle:[featureNameArray objectAtIndex:i] forState:UIControlStateNormal];
        //  [button setTitleColor:[UIColor colorWithRed:80.0f/255.0f green:80.0f/255.0f blue:80.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(tagButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_tagView addSubview:button];
    }
 
    _tagView.frame=frame;
    CGRect frame1=_lastView.frame;
    frame1.origin.y=_tagView.frame.origin.y+_tagView.frame.size.height;
    _lastView.frame=frame1;
}
-(void)tagButtonClick:(UIButton *)sender
{
    
    [sender setBackgroundColor:[UIColor colorWithRed:254.0f/255.0f green:249.0f/255.0f blue:228.0f/255.0f alpha:1.0f]];
    sender.layer.borderWidth=1;
    sender.layer.borderColor=[[UIColor colorWithRed:226.0f/255.0f green:208.0f/255.0f blue:166.0f/255.0f alpha:1.0f] CGColor];
    [sender setTitleColor:[UIColor colorWithRed:209.0f/255.0f green:174.0f/255.0f blue:80.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];
    if (![selectFeatureCodeArray containsObject:[featureCodeArray objectAtIndex:sender.tag]]) {
        
        [selectFeatureCodeArray addObject:[featureCodeArray objectAtIndex:sender.tag]];
        [selectFeatureNameArray addObject:[featureNameArray objectAtIndex:sender.tag]];
        sender.layer.borderColor=[[UIColor colorWithRed:226.0f/255.0f green:208.0f/255.0f blue:166.0f/255.0f alpha:1.0f] CGColor];
        sender.layer.borderWidth= 1.0f;
        [sender setTitleColor:[UIColor colorWithRed:209.0f/255.0f green:174.0f/255.0f blue:80.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];
    }
    else
    {
        [selectFeatureCodeArray removeObject:[featureCodeArray objectAtIndex:sender.tag]];
        [selectFeatureNameArray removeObject:[featureNameArray objectAtIndex:sender.tag]];
        sender.layer.borderColor=[[UIColor colorWithRed:239.0f/255.0f green:239.0f/255.0f blue:239.0f/255.0f alpha:1.0f] CGColor];
        sender.layer.borderWidth= 1.0f;
        [sender setBackgroundColor:[UIColor clearColor]];
        [sender setTitleColor:[UIColor colorWithRed:100.0f/255.0f green:100.0f/255.0f blue:100.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];
        
    }
    // NSLog(@"selectCodeArray====%@",selectCodeArray);
}
-(IBAction)oneDatePickerValueChanged:(UIDatePicker *)sender
{
    NSDate *selectedDate =[sender date];
    //NSLog(@"curDate is %@" ,selectedDate);
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];//修改时区为东8区
    
    NSString *destDateString = [dateFormatter stringFromDate:selectedDate];
    _dateTextField.text=destDateString;
    
    // NSLog(@"destDateString is %@" ,destDateString);
}

-(IBAction)birthViewConfirmClick:(id)sender
{
    [UIView animateWithDuration:0.5f animations:^
     {
         CGRect viewFrame=_addGuideBirthViewContainer.frame;
         viewFrame.origin.y=768;
         _addGuideBirthViewContainer.frame=viewFrame;
     }completion:^(BOOL finished) {
         
         
     }];
    
    NSDate *selectedDate =[_datePicker date];
    //NSLog(@"curDate is %@" ,selectedDate);
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];//修改时区为东8区
    
    NSString *destDateString = [dateFormatter stringFromDate:selectedDate];
    _dateTextField.text=destDateString;
    
    
}

-(void)cancelLocatePicker
{
    [self.locatePicker cancelPicker];
    self.locatePicker.delegate = nil;
    self.locatePicker = nil;
}
#pragma mark - HZAreaPicker delegate
-(void)sureBtnClick
{
    CGRect viewFrame=_addGuideAreaContainer.frame;
    viewFrame.origin.y=768;
    _addGuideAreaContainer.frame=viewFrame;
    
    self.areaValue = [NSString stringWithFormat:@"%@ %@ %@", self.locatePicker.locate.state, self.locatePicker.locate.city, self.locatePicker.locate.district];
    _addGuideAreaTextField.text=self.areaValue ;
    provinceStr=[NSString stringWithFormat:@"%@",self.locatePicker.locate.state];
    cityStr=[NSString stringWithFormat:@"%@",self.locatePicker.locate.city];
    regionStr=[NSString stringWithFormat:@"%@",self.locatePicker.locate.district];
    //  NSLog(@"regionstr===%@",regionStr);
    // NSString *address=[NSString stringWithFormat:@"%@%@%@", self.locatePicker.locate.state, self.locatePicker.locate.city, self.locatePicker.locate.district];
    // _addGuideAddressTextField.text=[NSString stringWithFormat:@"%@",address];
    
    
    [self cancelLocatePicker];
    
}
-(void)pickerDidChaneStatus:(HZAreaPickerView *)picker
{
    if (picker.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        self.areaValue = [NSString stringWithFormat:@"%@ %@ %@", picker.locate.state, picker.locate.city, picker.locate.district];
        _addGuideAreaTextField.text=self.areaValue ;
        provinceStr=[NSString stringWithFormat:@"%@",picker.locate.state];
        cityStr=[NSString stringWithFormat:@"%@",picker.locate.city];
        regionStr=[NSString stringWithFormat:@"%@",picker.locate.district];
        //  NSLog(@"regionstr===%@",regionStr);
        //        NSString *address=[NSString stringWithFormat:@"%@%@%@", picker.locate.state, picker.locate.city, picker.locate.district];
        //        _addGuideAddressTextField.text=[NSString stringWithFormat:@"%@",address];
    }
}

-(IBAction)saveGuideBtnClick:(id)sender
{
    // NSLog(@"44444444");
    if ([self validateMobile:_addGuidePhoneTextField.text]&&_nameTextField.text.length>0&&_dateTextField.text.length>0&&_userNameTextField.text.length>0)
    {
        if ([Global getLoginToken].length>0) {
            [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
            NSMutableArray *mDocumentLine=[NSMutableArray array];
            for (int i=0; i<selectFeatureCodeArray.count; i++) {
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                NSString *codeStr = [selectFeatureCodeArray objectAtIndex:i];
                NSString *nameStr = [selectFeatureNameArray objectAtIndex:i];
                [dic setValue:codeStr forKey:@"FeatureCode"];
                [dic setValue:nameStr forKey:@"FeatureName"];
                
                [mDocumentLine addObject:dic];
            }
            NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
            [params setObject:[Global getLoginToken] forKey:@"Token"];
            //[params setObject:@"A" forKey:@"EditType"];
            [params setObject:_nameTextField.text forKey:@"GuideName"];
            [params setObject:provinceStr forKey:@"ProvinceName"];
            [params setObject:cityStr forKey:@"CityName"];
            [params setObject:regionStr forKey:@"RegionName"];
            [params setObject:_addGuideAddressTextField.text forKey:@"Address"];
            [params setObject:_dateTextField.text forKey:@"OnBoardDate"];
            [params setObject:_addGuidePhoneTextField.text forKey:@"Phone"];
            [params setObject:_userNameTextField.text forKey:@"LoginName"];
            [params setObject:sexStr forKey:@"Sex"];
            [params setObject:_remarkTextView.text forKey:@"Remark"];
            
            [params setObject:mDocumentLine forKey:@"DataLine"];
          
            
            [HttpRequest requestData:@"ShopManager/AddGuide" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
                      
                        for (UIButton *button in _tagView.subviews) {
                            // [button removeFromSuperview];
                            button.layer.borderColor=[[UIColor colorWithRed:252.0f/255.0f green:165.0f/255.0f blue:0.0f/255.0f alpha:1] CGColor];
                            button.layer.borderWidth= 0.0f;
                        }
                        if (self.view!=nil) {
                            [self.view removeFromSuperview];
                            [self removeFromParentViewController];
                            
                        }

                        if ([self.delegate respondsToSelector:@selector(saveGuideSuccess)]) {
                            [self.delegate saveGuideSuccess];
                        }
                    }
                    else
                    {
                        [Global hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        //  [Global showTextHud:requestResultStr view:self.view];
                        [Global showTextHudSub:requestResultStr view:self.view];
                        if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                            
                            [Global loginViewController:self noteStr:requestResultStr];
                            //[Global loginViewController:self];
                        }
                        
                    }
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    [Global showTextHudSub:@"连接失败" view:self.view];
                }
            }];
            
        }
        
    }
    else
    {
        if ( _nameTextField.text.length==0)
        {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请填写姓名" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            //&&sexStr.length>0
        }
        
        else if (![self validateMobile:_addGuidePhoneTextField.text]) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请填写正确的手机号码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            
        }
        else if ( _dateTextField.text.length==0)
        {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请填写入职日期" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            
        }
          else if (_userNameTextField.text.length==0)
          {
              UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请填写用户名" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
              [alert show];
          }
    }
    
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:_addGuideAreaTextField]) {
        [_userNameTextField resignFirstResponder];
        [_nameTextField resignFirstResponder];
        [_addGuideAddressTextField resignFirstResponder];
        [_addGuidePhoneTextField resignFirstResponder];
        //[_areaTextField resignFirstResponder];
        [_remarkTextView resignFirstResponder];
        
        [UIView animateWithDuration:0.5f animations:^
         {
             CGRect viewFrame=_addGuideAreaContainer.frame;
             viewFrame.origin.y=71;
             _addGuideAreaContainer.frame=viewFrame;
         }completion:^(BOOL finished) {
             
             
         }];
        [self cancelLocatePicker];
        self.locatePicker = [[HZAreaPickerView alloc] initWithStyle:HZAreaPickerWithStateAndCityAndDistrict delegate:self];
        [self.locatePicker showInView:_addGuideAreaView];
        return NO;
    }
    else if ([textField isEqual:_dateTextField])
    {
        [_userNameTextField resignFirstResponder];
        [_nameTextField resignFirstResponder];
        //[_addressTextField resignFirstResponder];
        //[_phoneTextField resignFirstResponder];
        //[_areaTextField resignFirstResponder];
        [_remarkTextView resignFirstResponder];
        // NSLog(@"5555566666666");
        
        [_addGuideAddressTextField resignFirstResponder];
        [_addGuidePhoneTextField resignFirstResponder];
        [UIView animateWithDuration:0.5f animations:^
         {
             CGRect viewFrame=_addGuideBirthViewContainer.frame;
             viewFrame.origin.y=70;
             _addGuideBirthViewContainer.frame=viewFrame;
         }completion:^(BOOL finished) {
             
             
         }];
        return NO;
        
    }
    
    
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_nameTextField resignFirstResponder];
    
    [_remarkTextView resignFirstResponder];
    // NSLog(@"5555566666666");
    [_nameTextField resignFirstResponder];
    [_addGuideAddressTextField resignFirstResponder];
    [_addGuidePhoneTextField resignFirstResponder];
    
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length == 0) {
        _remarkTextViewImage.hidden=NO;
        _remarkTextViewLabel.hidden=NO;
        
    }
    else
    {
        _remarkTextViewImage.hidden=YES;
        _remarkTextViewLabel.hidden=YES;
        
    }

}
-(void)textViewBeginInput
{
    
    [UIView animateWithDuration:0.3 animations:^{
        CGFloat offset=0.0;
        CGRect frameA=_lastView.frame;
        frameA.origin.y=768-([Global getKeyboardHeight]+_remarkTextView.frame.size.height+_remarkTextView.frame.origin.y);
        
        offset=frameA.origin.y-_lastView.frame.origin.y;
        
        
       
        CGRect viewFrame=_mainView.frame;
        viewFrame.origin.y=offset;
        _mainView.frame=viewFrame;
        
    } completion:^(BOOL finished){
        
    }];
    
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
     [self performSelector:@selector(textViewBeginInput) withObject:nil afterDelay:0.1];
     return YES;
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    
        [UIView animateWithDuration:0.3 animations:^{
            CGRect viewFrame=_mainView.frame;
            viewFrame.origin.y=0;
            _mainView.frame=viewFrame;
        } completion:^(BOOL finished){
            
        }];
        
 
    
}

- (BOOL)validateMobile:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|7[678]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    
    NSString *others=@"^1((4[57]|7[0]))\\d{8}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    NSPredicate *regextestothers = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", others];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES)||([regextestothers evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
